package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.Usermapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private Usermapper usermapper;

    @Override
    public User login(UserLoginDTO dto) {
        //1。通过HttpClient,构建登录凭证校验请求

        //构造请求参数
        Map<String,String> parammap=new HashMap<String,String>();
        parammap.put("appid",weChatProperties.getAppid());
        parammap.put("secret",weChatProperties.getSecret());
        parammap.put("js_code",dto.getCode());
        parammap.put("grant_type","authorization_code");

        //调用HttpClientUtil工具类，发送请求
        String res= HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",parammap);
        log.info("res={}",res);
        //2。解析响应结果，获取oppenid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if(openid==null){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        //3。判断是否为新用户，根据openid查询user表
        User user=usermapper.selectByOpenid(openid);
        //4。如果是新用户，初始化用户数据到user表
           if(user==null){
             user =new User();
             user.setOpenid(openid);
             user.setCreateTime(LocalDateTime.now());
             user.setName(openid.substring(0,5));
               usermapper.insert(user);
           }

        //5。否杂，直接返回user对象数据


        return user;
    }
}
